package dhm.com.dhmshop.fragment.wode;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.ColorDrawable;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import com.jcodecraeer.xrecyclerview.XRecyclerView;
import com.tencent.mm.opensdk.constants.ConstantsAPI;
import com.tencent.mm.opensdk.modelbase.BaseReq;
import com.tencent.mm.opensdk.modelbase.BaseResp;
import com.tencent.mm.opensdk.modelpay.PayReq;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.IWXAPIEventHandler;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;
import dhm.com.dhmshop.R;
import dhm.com.dhmshop.adapter.mine.FunctionAdapter;
import dhm.com.dhmshop.adapter.mine.MyOrderAdapter;
import dhm.com.dhmshop.entity.FunctionBean;
import dhm.com.dhmshop.entity.GetAllOrder;
import dhm.com.dhmshop.entity.ShopCarBean;
import dhm.com.dhmshop.entity.WacherBean;
import dhm.com.dhmshop.framework.module.commodity.activity.CommodityDetailsActivity;
import dhm.com.dhmshop.updata.activity.FunctionActivity;
import dhm.com.dhmshop.updata.activity.TopaydetailActivity;
import dhm.com.dhmshop.utils.TimeUtil;
import dhm.com.dhmshop.view.home.OrderdetailActivity;
import dhm.com.dhmshop.view.mine.AddressActivity;
import dhm.com.dhmshop.view.mine.order.LogisticsActivity;
import dhm.com.dhmshop.view.mine.order.ShowevaluateActivity;
import dhm.com.dhmshop.base.BaseFragment;
import dhm.com.dhmshop.base.Presenter.PressenterImpl;
import dhm.com.dhmshop.base.netWork.Constant;
import dhm.com.dhmshop.base.netWork.LoginContract;
import dhm.com.dhmshop.entity.Bean;
import dhm.com.dhmshop.entity.Myorder;
import dhm.com.dhmshop.utils.SpUtils;
import dhm.com.dhmshop.view.mine.AddaddrActivity;

import static android.app.Activity.RESULT_OK;

@SuppressLint("ValidFragment")
public class MyorderFragment extends BaseFragment implements LoginContract.IView , IWXAPIEventHandler {

    @BindView(R.id.recy)
    XRecyclerView recy;
    @BindView(R.id.linearimage)
    LinearLayout image;

    Unbinder unbinder;
    private String type;
    private String uid;
    private PressenterImpl pressenter;
    private MyOrderAdapter myOrderAdapter;
    private GetAllOrder myorder;
    private int offset;
    private List<GetAllOrder.DataBean> allorder;
    private String address_id = "";
    private int position;

    private PopupWindow mPopWindow;

    public MyorderFragment(String type) {
//        type 0:全部 1:代付款 2.待发货 3.待收货   4.待评价   5.已完成   6.取消拒收
        this.type = type;
    }

    @Override
    protected int getLayout() {
        return R.layout.fragment_myorder;
    }

    @Override
    protected void initView() {
        uid = SpUtils.getString(getActivity(), "uid");
        pressenter = new PressenterImpl();
        pressenter.attachView(this);
    }

    @Override
    protected void initData() {
        offset = 1;
        LinearLayoutManager manager = new LinearLayoutManager(getActivity());
        manager.setOrientation(LinearLayoutManager.VERTICAL);
        recy.setLayoutManager(manager);
        recy.setLoadingMoreEnabled(true);
        recy.setPullRefreshEnabled(true);
        recy.setLoadingListener(new XRecyclerView.LoadingListener() {
            @Override
            public void onRefresh() {
                offset = 1;
                search();
            }

            @Override
            public void onLoadMore() {
                search();
            }
        });
        search();
    }

    private void search() {
        Map<String, String> map = new HashMap<>();
        map.put("uid", uid);
        map.put("page", offset + "");
        map.put("token",Constant.TOKEN);
        switch (type) {
            case "0":
//                全部
                pressenter.sendMessage(getActivity(), Constant.Allorders, map, GetAllOrder.class);
                break;
            case "1":
//                代付款
                pressenter.sendMessage(getActivity(), Constant.AllordersToPay, map, GetAllOrder.class);
                break;
            case "2":
//                待发货
                pressenter.sendMessage(getActivity(), Constant.AllordersTodeliver, map, GetAllOrder.class);
                break;
            case "3":
//                待收货
                pressenter.sendMessage(getActivity(), Constant.Allordersdeliver, map, GetAllOrder.class);
                break;
            case "4":
//                待评价
                pressenter.sendMessage(getActivity(), Constant.AllordersToEvaluate, map, GetAllOrder.class);
                break;
            case "5":
//                已完成
                pressenter.sendMessage(getActivity(), Constant.AllOrdersFinish, map, GetAllOrder.class);
                break;
            case "6":
//                取消拒收
                pressenter.sendMessage(getActivity(), Constant.CancleOrdersList, map, GetAllOrder.class);
                break;
            default:
        }
    }


    @Override
    public void requesta(Object data) {
        if (data instanceof GetAllOrder) {
            myorder = (GetAllOrder) data;
            if (myorder.getCode() == 1) {

                recy.setVisibility(View.VISIBLE);
                image.setVisibility(View.GONE);
                if (offset==1) {
                    myOrderAdapter = new MyOrderAdapter(getActivity(), type);
                    allorder = myorder.getData();
                    switch (type) {
                        case "0":
//                全部
                            break;
                        case "1":
//                代付款
                            myOrderAdapter.setdeleteClick(new MyOrderAdapter.OnClick() {
                                @Override
                                public void item(int posttion) {
//                                    取消订单
                                    position = posttion;
//                                    showPopwindow();CancelOrdersReason

                                    Map<String, String> map = new HashMap<>();
                                    map.put("token", Constant.TOKEN);
                                    pressenter.sendMessage(getActivity(), Constant.CancelOrdersReason, map, FunctionBean.class);


                                }
                            });

                            myOrderAdapter.setaddClick(new MyOrderAdapter.OnIntentClick() {
                                @Override
                                public void item(int posttion) {
                                    Intent intent=new Intent(getActivity(), TopaydetailActivity.class);
                                    intent.putExtra("orderbean",allorder.get(posttion));
                                    getActivity().startActivity(intent);
                                }
                            });


                            break;
                        case "2":
//                待发货
                            myOrderAdapter.setdeleteClick(new MyOrderAdapter.OnClick() {
                                @Override
                                public void item(int posttion) {
//                                    催发货
                                    Map<String, String> map1 = new HashMap<>();
                                    map1.put("token", Constant.TOKEN);
                                    map1.put("order_id", allorder.get(posttion).getOrderId()+"");
                                    map1.put("uid", uid+"");
                                    pressenter.sendMessage(getActivity(), Constant.AddSendOrder, map1, Bean.class);
                                }
                            });
                            myOrderAdapter.setaddClick(new MyOrderAdapter.OnShopClick() {
                                @Override
                                public void item(int posttion) {
//                                    取消订单
                                    position = posttion;
                                    Map<String, String> map = new HashMap<>();
                                    map.put("token", Constant.TOKEN);
                                    pressenter.sendMessage(getActivity(), Constant.CancelOrdersReason, map, FunctionBean.class);
                                }
                            });



                            break;
                        case "3":
//                待收货
                            myOrderAdapter.setaddClick(new MyOrderAdapter.OnShopClick() {
                                @Override
                                public void item(int posttion) {
//                        确认收货
                                    Map<String, String> map1 = new HashMap<>();
                                    map1.put("token", Constant.TOKEN);
                                    map1.put("uid",uid);
                                    map1.put("order_id", allorder.get(posttion).getOrderId() + "");
                                    pressenter.sendMessage(getActivity(), Constant.OrderOver, map1, Bean.class);
                                }
                            });
                            myOrderAdapter.setaddClick(new MyOrderAdapter.OnIntentClick() {
                                @Override
                                public void item(int posttion) {
//                                    拒收
                                    position = posttion;
//                                    showPopwindow();
                                    Map<String, String> map = new HashMap<>();
                                    map.put("token", Constant.TOKEN);
                                    pressenter.sendMessage(getActivity(), Constant.RejrctReason, map, FunctionBean.class);
                                }
                            });


                            break;
                        case "4":
//                待评价
                            break;
                        default:
                    }
                    recy.setAdapter(myOrderAdapter);
                } else {
                    allorder.addAll(myorder.getData());
                }
                offset++;
                myOrderAdapter.setShopList(allorder);
            }else if (myorder.getCode() == -2){
                recy.setVisibility(View.GONE);
                image.setVisibility(View.VISIBLE);
            }
            if (allorder==null||allorder.size()==0){
                recy.setVisibility(View.GONE);
                image.setVisibility(View.VISIBLE);
            }
            recy.loadMoreComplete();
            recy.refreshComplete();
        } else if (data instanceof Bean) {
            Bean bean = (Bean) data;
            Toast.makeText(getActivity(), bean.getMessage(), Toast.LENGTH_SHORT).show();
            if (bean.getCode()==1){
                offset=1;
                search();
            }
        }else if (data instanceof FunctionBean) {
            functionBean = (FunctionBean) data;
            showPopwindow();
        }

    }
    private String typeid = "";
    private FunctionBean functionBean;
    private FunctionAdapter functionAdapter;
    private PopupWindow popWindow;
    private void showPopwindow() {
        View popView = View.inflate(getActivity(), R.layout.popup_questiontype, null);
        Button sure = popView.findViewById(R.id.sure);
        RecyclerView recy = popView.findViewById(R.id.recy);
        LinearLayoutManager manager = new LinearLayoutManager(getActivity());
        manager.setOrientation(LinearLayoutManager.VERTICAL);
        functionAdapter = new FunctionAdapter(getActivity());
        functionAdapter.setaddClick(new FunctionAdapter.OnShopClick() {
            @Override
            public void item(List<FunctionBean.DataBean> beanList) {
                functionBean.setData(beanList);
                functionAdapter.setShopList(functionBean.getData());
            }
        });

        recy.setAdapter(functionAdapter);
        recy.setLayoutManager(manager);
        functionAdapter.setShopList(functionBean.getData());
        sure.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                switch (type) {
                    case "0":
//                全部
                        break;
                    case "1":
//                代付款

                        for (int i = 0; i < functionBean.getData().size(); i++) {
                            if (functionBean.getData().get(i).isChecked()) {
                                typeid = functionBean.getData().get(i).getDataVal() + "";
                                Map<String,String> map=new HashMap<>();
                                map.put("token",Constant.TOKEN);
                                map.put("order_id",allorder.get(position).getOrderId()+"");
                                map.put("reason",functionBean.getData().get(i).getDataVal()+"");
                                map.put("uid",uid);
                                pressenter.sendMessage(getActivity(),Constant.CancelOrder,map,Bean.class);

                            }
                        }

                        if (typeid.equals("")) {
                            Toast.makeText(getActivity(), "请选择取消订单的原因", Toast.LENGTH_SHORT).show();
                            return;
                        }
                        break;
                    case "2":
//                待发货
                        for (int i = 0; i < functionBean.getData().size(); i++) {
                            if (functionBean.getData().get(i).isChecked()) {
                                typeid = functionBean.getData().get(i).getDataVal() + "";
                                Map<String,String> map=new HashMap<>();
                                map.put("token",Constant.TOKEN);
                                map.put("order_id",allorder.get(position).getOrderId()+"");
                                map.put("reason",functionBean.getData().get(i).getDataVal()+"");
                                map.put("uid",uid);
                                pressenter.sendMessage(getActivity(),Constant.CancelOrder,map,Bean.class);

                            }
                        }

                        if (typeid.equals("")) {
                            Toast.makeText(getActivity(), "请选择取消订单的原因", Toast.LENGTH_SHORT).show();
                            return;
                        }
                        break;
                    case "3":
//                待收货

                        for (int i = 0; i < functionBean.getData().size(); i++) {
                            if (functionBean.getData().get(i).isChecked()) {
                                typeid = functionBean.getData().get(i).getDataVal() + "";
                                Map<String,String> map=new HashMap<>();
                                map.put("token",Constant.TOKEN);
                                map.put("order_id",allorder.get(position).getOrderId()+"");
                                map.put("reason",functionBean.getData().get(i).getDataVal()+"");
                                map.put("uid",uid);
                                pressenter.sendMessage(getActivity(),Constant.Reject,map,Bean.class);

                            }
                        }

                        if (typeid.equals("")) {
                            Toast.makeText(getActivity(), "请选择拒收的原因", Toast.LENGTH_SHORT).show();
                            return;
                        }

                        break;
                    case "4":
//                待评价
                        break;
                    default:
                }

                popWindow.dismiss();
            }
        });


        popWindow = new PopupWindow(popView, ViewGroup.LayoutParams.MATCH_PARENT,
                ViewGroup.LayoutParams.WRAP_CONTENT, true);
        popWindow.setAnimationStyle(R.style.AnimBottom);
        popWindow.setFocusable(true);
        popWindow.setTouchable(true);
        popWindow.setBackgroundDrawable(new BitmapDrawable());
        popWindow.setOutsideTouchable(true);// 设置允许在外点击消失


        popWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                // popupWindow隐藏时恢复屏幕正常透明度
                setBackgroundAlpha(1.0f);
            }
        });
        setBackgroundAlpha(0.5f);
        popWindow.showAtLocation(popView, Gravity.BOTTOM, 0, 0);
    }

    /**
     * 设置添加屏幕的背景透明度
     *
     * @param bgAlpha 屏幕透明度0.0-1.0 1表示完全不透明
     */
    public void setBackgroundAlpha(float bgAlpha) {
        WindowManager.LayoutParams lp = getActivity().getWindow()
                .getAttributes();
        lp.alpha = bgAlpha;
        getActivity().getWindow().setAttributes(lp);
    }









    private static final int MY_PERMISSIONS_CALL_PHONE = 1;
    @Override
    public void fail(String error) {

    }

    private View rootView;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        if (rootView == null) {
            rootView = inflater.inflate(R.layout.fragment_myorder, container, false);
        }
        unbinder = ButterKnife.bind(this, rootView);
        initView();
        return rootView;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case 200:
                if (resultCode == RESULT_OK) {
                    address_id = data.getIntExtra("address_id", 0) + "";
                    if (!address_id.equals("0")) {
                        String name = data.getStringExtra("name");
                        String phone = data.getStringExtra("phone");
                        String address = data.getStringExtra("address");

                        Map<String, String> map = new HashMap<>();
                        map.put("token", Constant.TOKEN);
                        map.put("uid", uid);
                        map.put("shop_id", allorder.get(position).getShopId() + "");
                        map.put("order_id", allorder.get(position).getOrderId() + "");
                        map.put("address_id", address_id);
                        pressenter.sendMessage(getActivity(), Constant.OrderAddressModify, map, Bean.class);
                    }
                }
                break;
            default:
        }

    }

    @Override
    public void onReq(BaseReq baseReq) {

    }

    @Override
    public void onResp(BaseResp resp) {
        if (resp.getType() == ConstantsAPI.COMMAND_PAY_BY_WX) {
            switch (resp.errCode) {
                case 0://支付成功
                    Toast.makeText(getActivity(), "支付成功", Toast.LENGTH_SHORT).show();
                    offset=1;
                    search();
                    break;
                case -1://错误，可能的原因：签名错误、未注册APPID、项目设置APPID不正确、注册的APPID与设置的不匹配、其他异常等
                    Toast.makeText(getActivity(), "支付错误" + resp.errCode, Toast.LENGTH_SHORT).show();
                    break;
                case -2://用户取消，无需处理。发生场景：用户不支付了，点击取消，返回APP。
                    Toast.makeText(getActivity(), "用户取消" + resp.errCode, Toast.LENGTH_SHORT).show();
                    break;
                    default:
            }

//            finish();//这里需要关闭该页面
        }

    }
}
